from flask import Blueprint, jsonify, request, send_file
import pandas as pd
import numpy as np
from pathlib import Path
import os
import sys
import traceback
from own_vehicle_analysis import main as analyze_data
import json

# 创建蓝图
own_vehicle_bp = Blueprint('own_vehicle', __name__)

def get_resource_path(relative_path):
    """获取资源文件的绝对路径，支持开发环境和打包环境"""
    if hasattr(sys, '_MEIPASS'):
        # PyInstaller 打包环境
        base_path = sys._MEIPASS
    else:
        # 开发环境
        base_path = os.path.dirname(os.path.abspath(__file__))
    
    return os.path.join(base_path, relative_path)

# 配置常量
DATA_DIR = Path("data")
OUTPUT_DIR = DATA_DIR / "alldata"
RESULT_FILE = OUTPUT_DIR / "自带车报销交通补助分析结果.xlsx"

def handle_nan_values(obj):
    """处理数据中的NaN值"""
    if isinstance(obj, (pd.Series, pd.DataFrame)):
        return obj.where(pd.notnull(obj), None)
    elif isinstance(obj, dict):
        return {k: handle_nan_values(v) for k, v in obj.items()}
    elif isinstance(obj, list):
        return [handle_nan_values(item) for item in obj]
    elif pd.isna(obj) or (isinstance(obj, float) and np.isnan(obj)):
        return None
    return obj

@own_vehicle_bp.route('/check-result-file', methods=['GET'])
def check_result_file():
    """检查结果文件是否存在"""
    try:
        exists = RESULT_FILE.exists()
        return jsonify({'exists': exists})
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@own_vehicle_bp.route('/generate-analysis', methods=['POST'])
def generate_analysis():
    """生成分析数据"""
    try:
        # 确保输出目录存在
        OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
        
        # 运行分析
        success = analyze_data()
        
        if success:
            return jsonify({'success': True})
        else:
            return jsonify({'success': False, 'error': '分析过程中出现错误'})
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@own_vehicle_bp.route('/get-data', methods=['POST'])
def get_data():
    """获取分析数据"""
    try:
        if not RESULT_FILE.exists():
            return jsonify({'error': '数据文件不存在'}), 404

        # 读取Excel文件
        df = pd.read_excel(RESULT_FILE)
        
        # 确保分录编号和辅助编号为4位字符串格式
        for col in ['分录编号', '辅助编号']:
            if col in df.columns:
                df[col] = df[col].astype(str).str.zfill(4)
        
        # 处理数据中的NaN值
        df = df.replace({np.nan: None})
        
        # 转换为字典列表并处理NaN值
        data = df.to_dict('records')
        data = handle_nan_values(data)
        # 获取所有列名
        all_columns = df.columns.tolist()
        print(all_columns)
        return jsonify({
            'data': data,
            'all_columns': all_columns
        })

    except Exception as e:
        return jsonify({'error': str(e)}), 500

from flask import current_app

@own_vehicle_bp.route('/download-excel', methods=['POST'])
def download_excel():
    """下载Excel文件"""
    try:
        # 获取选定的字段和筛选后的数据
        selected_fields = request.form.getlist('fields')
        if not RESULT_FILE.exists():
            return jsonify({'error': '数据文件不存在'}), 404

        # 读取Excel文件
        df = pd.read_excel(RESULT_FILE)

        if selected_fields:
            # 只保留选定的列
            df = df[selected_fields]

        # 确保分录编号和辅助编号为4位字符串格式
        for col in ['分录编号', '辅助编号']:
            if col in df.columns:
                df[col] = df[col].astype(str).str.zfill(4)

        # 创建临时文件名，使用时间戳确保唯一性
        timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
        filename = f"自带车报销交通补助分析结果_{timestamp}.xlsx"

        # 创建临时目录用于存放下载文件
        temp_dir = Path(get_resource_path('temp'))
        temp_dir.mkdir(parents=True, exist_ok=True)
        temp_file = temp_dir / filename

        try:
            # 使用ExcelWriter保存文件，设置特定列的格式
            with pd.ExcelWriter(temp_file, engine='openpyxl', mode='w') as writer:
                df.to_excel(writer, index=False)

                # 设置分录编号和辅助编号列为文本格式
                if any(col in df.columns for col in ['分录编号', '辅助编号']):
                    worksheet = writer.sheets['Sheet1']
                    for idx, col in enumerate(df.columns):
                        if col in ['分录编号', '辅助编号']:
                            # 设置整列为文本格式
                            col_letter = chr(65 + idx)  # 将列索引转换为Excel列字母
                            worksheet.column_dimensions[col_letter].number_format = '@'
                            # 设置每个单元格为文本格式
                            for row in range(2, len(df) + 2):  # Excel是1-based，第一行是标题
                                cell = worksheet.cell(row=row, column=idx + 1)
                                cell.number_format = '@'  # 设置单元格格式为文本
                                # 确保单元格的值是字符串格式
                                if cell.value is not None:
                                    cell.value = str(cell.value).zfill(4)

            response = send_file(
                temp_file,
                as_attachment=True,
                download_name=filename,
                mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
            )

            # 设置回调以在发送后删除临时文件
            @response.call_on_close
            def cleanup():
                try:
                    if temp_file.exists():
                        temp_file.unlink()
                except Exception as e:
                    print(f"清理临时文件时出错: {str(e)}")

            return response

        except Exception as e:
            # 如果出错，确保清理临时文件
            if temp_file.exists():
                try:
                    temp_file.unlink()
                except:
                    pass
            return jsonify({
                'error': f'保存文件时出错: {str(e)}'
            }), 500
        # filtered_data = request.form.get('data')
        
        # if not filtered_data:
        #     return jsonify({'error': '没有数据可供下载'}), 400
            
        # # 将JSON字符串转换为Python对象
        # filtered_data = json.loads(filtered_data)
        
        # if not filtered_data:
        #     return jsonify({'error': '没有数据可供下载'}), 400
            
        # # 创建DataFrame
        # df = pd.DataFrame(filtered_data)
        
        # if selected_fields:
        #     # 只保留选定的列
        #     df = df[selected_fields]

        # # 创建临时文件名，使用时间戳确保唯一性
        # from datetime import datetime
        # timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
        # filename = f"自带车报销交通补助分析结果_{timestamp}.xlsx"
        
        # # 创建临时目录用于存放下载文件
        # temp_dir = Path(get_resource_path('temp'))
        # temp_dir.mkdir(parents=True, exist_ok=True)
        # temp_file = temp_dir / filename
        
        # try:
        #     # 使用ExcelWriter保存文件，设置特定列的格式
        #     with pd.ExcelWriter(temp_file, engine='openpyxl', mode='w') as writer:
        #         df.to_excel(writer, index=False)
                
        #         # 设置分录编号和辅助编号列为文本格式
        #         if any(col in df.columns for col in ['分录编号', '辅助编号']):
        #             worksheet = writer.sheets['Sheet1']
        #             for idx, col in enumerate(df.columns):
        #                 if col in ['分录编号', '辅助编号']:
        #                     # 设置整列为文本格式
        #                     col_letter = chr(65 + idx)  # 将列索引转换为Excel列字母
        #                     worksheet.column_dimensions[col_letter].number_format = '@'
        #                     # 设置每个单元格为文本格式
        #                     for row in range(2, len(df) + 2):  # Excel是1-based，第一行是标题
        #                         cell = worksheet.cell(row=row, column=idx + 1)
        #                         cell.number_format = '@'  # 设置单元格格式为文本
        #                         # 确保单元格的值是字符串格式
        #                         if cell.value is not None:
        #                             cell.value = str(cell.value).zfill(4)
            
        #     response = send_file(
        #         temp_file,
        #         as_attachment=True,
        #         download_name=filename,
        #         mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        #     )
            
            # # 设置回调以在发送后删除临时文件
            # @response.call_on_close
            # def cleanup():
            #     try:
            #         if temp_file.exists():
            #             temp_file.unlink()
            #     except Exception as e:
            #         print(f"清理临时文件时出错: {str(e)}")
            
            # return response
            
        except Exception as e:
            # 如果出错，确保清理临时文件
            if temp_file.exists():
                try:
                    temp_file.unlink()
                except:
                    pass
            return jsonify({
                'error': f'保存文件时出错: {str(e)}'
            }), 500

    except Exception as e:
        print(f"下载文件时出错: {str(e)}")
        traceback.print_exc()
        return jsonify({
            'error': f'下载文件时出错: {str(e)}'
        }), 500 